package com.yonyou.hxjy.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class BuildToken {


    public String getToken(String APP_ID,String app_secret,String grant_type,String TARGET_URL) throws Exception {

        // 检查配置参数
        System.out.println(APP_ID);
        System.out.println(app_secret);
        System.out.println(grant_type);

        if (APP_ID == null || app_secret == null || grant_type == null) {
            throw new Exception("配置参数（APP_ID/app_secret/grant_type）不能为 null");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("app_id", APP_ID);
        map.put("app_secret", app_secret);
        map.put("grant_type", grant_type);

        String uri = TARGET_URL + "/openapi/app/v1/app/token";
        String requestBody = JSONObject.toJSONString(map);

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json");

        try {
            // 发送 HTTP 请求
            String response = HttpClientUtil.doPostJson(uri, requestBody, headerMap);
            if (response == null || response.isEmpty()) {
                throw new Exception("HTTP 请求返回空响应");
            }

            // 解析 JSON
            JSONObject jsonObject = JSONObject.parseObject(response);
            if (jsonObject == null) {
                throw new Exception("JSON 解析失败，返回数据格式不正确");
            }

            // 检查 code 字段
            String code = jsonObject.getString("code");
            if (code == null) {
                throw new Exception("返回数据缺少 code 字段");
            }
            if (!"0".equals(code)) {
                throw new Exception(jsonObject.getString("msg"));
            }

            // 提取 token
            JSONObject data = jsonObject.getJSONObject("data");
            if (data == null) {
                throw new Exception("返回数据缺少 data 字段");
            }
            String token = data.getString("token");
            if (token == null) {
                throw new Exception("返回数据缺少 token 字段");
            }

            return token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("获取 Token 失败: " + e.getMessage(), e);
        }
    }
}
